package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"mall-go/common"
	"mall-go/dto"
	"mall-go/model"
	"mall-go/repository"
	"mall-go/response"
)

type ManageUserController struct {
	DB *gorm.DB
}

// Login 登录
func (receiver ManageUserController) Login(ctx *gin.Context) {
	managerUserRepo := repository.NewManagerUserRepo()
	var loginParam dto.LoginParam
	//数据校验
	if err := ctx.ShouldBind(&loginParam); err != nil {
		panic(err)
	}
	flag, result := managerUserRepo.Login(loginParam)
	if flag == "Success" && result != "" {
		response.Success(ctx, gin.H{"token": result}, "登录成功")
		return
	}
	response.Failure(ctx, nil, result)
}

// Profile 获取个人资料
func (receiver ManageUserController) Profile(ctx *gin.Context) {
	//获取用户信息
	user, _ := ctx.Get("adminUser")
	adminUser := user.(model.NewBeeAdminUser)
	if adminUser.AdminUserId != 0 {
		adminUser.LoginPassword = "******"
		response.Success(ctx, gin.H{"user": adminUser}, "Success")
		return
	}
	response.Failure(ctx, nil, "数据不存在")
}

// UpdatePassword 修改密码
func (receiver ManageUserController) UpdatePassword(ctx *gin.Context) {
	//取出管理员id
	user, _ := ctx.Get("adminUser")
	adminUserId := user.(model.NewBeeAdminUser).AdminUserId
	managerUserRepo := repository.NewManagerUserRepo()
	var updateParam dto.UpdatePasswordParam
	//校验数据并绑定
	if err := ctx.ShouldBind(&updateParam); err != nil {
		//后面可以把这个错误信息描述的更清晰一点方便前端查错
		panic(err)
	}

	//修改密码
	flag := managerUserRepo.UpdatePassword(adminUserId, updateParam.OriginalPassword, updateParam.NewPassword)
	if flag {
		response.Success(ctx, nil, "修改成功")
	} else {
		response.Failure(ctx, nil, "数据不存在")
	}
}

// UpdateName 修改用户名
func (receiver ManageUserController) UpdateName(ctx *gin.Context) {
	//取出管理员id
	user, _ := ctx.Get("adminUser")
	adminUserId := user.(model.NewBeeAdminUser).AdminUserId //todo 在gin框架上下文中冗余存储一个用户id可以减少大量重复代码
	var nameParam dto.UpdateNameParam
	if err := ctx.ShouldBind(&nameParam); err != nil {
		panic(err)
	}
	managerUserRepo := repository.NewManagerUserRepo()
	flag := managerUserRepo.UpdateName(adminUserId, nameParam.LoginUserName, nameParam.NickName)
	if flag {
		response.Success(ctx, nil, "修改成功")
	} else {
		response.Failure(ctx, nil, "数据不存在")
	}
}

// Logout 登出用户
func (receiver ManageUserController) Logout(ctx *gin.Context) {
	managerUserRepo := repository.NewManagerUserRepo()
	managerUserRepo.Logout()
	response.Success(ctx, nil, "退出成功")
}

func NewAdminManageUserController() ManageUserController {
	db := common.GetDB()
	db.AutoMigrate(model.NewBeeAdminUser{})
	return ManageUserController{DB: db}
}
